<template>
  <div>
    <Form ref="form" :rules="formValidate" :label-width="90" :model="form">
          <FormItem label="Folder Name" prop="folderName">
            <Input v-model="form.folderName" />
          </FormItem>
    </Form>
    <Row class="code-row-bg" justify="end" type="flex">
      <Button @click="cancel" style="margin-right:10px">Cancel</Button>
      <Button @click="save" type="primary">Save</Button>
    </Row>
  </div>
</template>
<script>
  import { fileApi } from "@/api/file.js";
  export default {
    name: 'CodeReviewListForm',
    components: {
    },
    props: {
      //是否为更新表单
      isUpdate: {
        type: Boolean,
        default: true
      },
      //更新的表单数据对象
      updateData: {
        type: Object
      },
      parentFolderId:{
        type: Number,
        default:0
      },
    },
    data() {
      return {
        //表单数据
        form: {
         folderName:null,
        },
        //表单验证
        formValidate: {
        folderName:[{ required: true, message: '请输入文件名称', trigger: 'blur' }],
        }
      };
    },
  watch: {
      updateData: function(newValue, oldValue) {
          this.$refs['form'].resetFields();
          if (this.isUpdate) {
              for (let k in this.form) {
                  this.$set(this.form, k, newValue[k]);
              }
              this.$set(this.form, 'id', newValue['id']);
          }
          this.form.folderName = newValue.fileName;
      },
      isUpdate: function(newValue, oldValue) {
          if (!newValue) {
              this.resetForm();
              this.$refs['form'].resetFields();
          }
      }
  },
    created() {},
    mounted() {},
    methods: {
      cancel() {
        this.$emit('on-form-close');
      },
      save() {
       this.$refs['form'].validate(valid => {
         if (valid) {
           if (this.isUpdate) {
            this.update();
           } else {
             this.add();
           }
         } else {
          this.$Message.error('参数验证错误，请仔细填写表单数据!');
         }
       });
      },
    resetForm() {
        this.form = {
          folderName:null,
        };
        this.$refs['form'].resetFields();
      },
      async add() {
        this.$Spin.show();
        let param = {
            folderName: this.form.folderName,
            parentFolderId: this.parentFolderId
        }
        let res = await fileApi.addFolder(param);
        this.$Message.success(res.msg);
        this.$Spin.hide();
        this.resetForm();
        this.$emit('on-form-close');
      },
      async update() {
        this.$Spin.show();
        let param = {
            fileNewName: this.form.folderName,
            fileId: this.updateData.id
        }
        let res = await fileApi.reNameFolder(param);
        this.$Message.success(res.msg);
        this.$Spin.hide();
        this.resetForm();
        this.$emit('on-form-close');
      }
    }
  };
</script>